﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Common.Helpers
{
    /// <summary>
    /// 随机数帮助类
    /// </summary>
    public static class RandomHelper
    {
        private static readonly Random globalRandom = new Random();
        [ThreadStatic]
        private static Random localRandom;

        /// <summary>
        /// 生成指定长度的数字密码
        /// </summary>
        public static string GenerateNumericPassword(int length)
        {
            if (length <= 0) throw new ArgumentException("长度必须大于0");

            var random = GetThreadSafeRandom();
            int minValue = (int)Math.Pow(10, length - 1);
            int maxValue = (int)Math.Pow(10, length);

            return random.Next(minValue, maxValue).ToString($"D{length}");
        }

        private static Random GetThreadSafeRandom()
        {
            if (localRandom == null)
            {
                int seed;
                lock (globalRandom)
                {
                    seed = globalRandom.Next();
                }
                localRandom = new Random(seed);
            }
            return localRandom;
        }
    }
}
